package com.wang.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.wang.common.core.constants.Constant;
import com.wang.common.core.enums.ExamListType;
import com.wang.common.security.exception.ServiceException;
import com.wang.friend.domain.exam.Exam;
import com.wang.friend.domain.exam.ExamQuestion;
import com.wang.friend.domain.exam.dto.ExamQueryDTO;
import com.wang.friend.domain.exam.dto.ExamRankDTO;
import com.wang.friend.domain.exam.vo.ExamRankVO;
import com.wang.friend.domain.exam.vo.ExamVO;
import com.wang.common.core.enums.ResultCode;
import com.wang.common.redis.service.RedisService;
import com.wang.friend.mapper.exam.ExamMapper;
import com.wang.friend.mapper.exam.ExamQuestionMapper;
import com.wang.friend.mapper.user.UserExamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.wang.common.core.constants.CacheConstants;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class ExamCacheManager {

    @Autowired
        private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamQuestionMapper examQuestionMapper;


    /**
     * 获取竞赛列表的大小
     * @param examListType 竞赛列表的类型 (0-->未完赛  1-->历史竞赛  2-->用户已报名的竞赛)
     * @param userId 用户id
     * @return 返回大小
     */
    public Long getListSize(Integer examListType,Long userId) {
        String examListKey = getExamListKey(examListType,userId);
        return redisService.getListSize(examListKey);
    }

    /**
     * 为缓存列表添加当前用户已经报名的竞赛
     * @param userId 用户id
     * @param examId 竞赛id
     */
    public void addUserExamCache(Long userId, Long examId){
        //拿到userid对应的key
        String userExamKey = getUserExamListKey(userId);
        //将新报名的竞赛id存入缓存中
        redisService.leftPushForList(userExamKey,examId);
    }
    /**
     * 从缓存中获取竞赛数据
     * @param examQueryDTO 需要查询的竞赛信息
     * @return 返回竞赛列表信息
     */
    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO, Long userId) {

        //开始下标
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
        //结束下标
        int end = start + examQueryDTO.getPageSize() - 1; //下标需要 -1

        //获取key
        String examListKey = getExamListKey(examQueryDTO.getType(),userId);

        //获取指定范围内的竞赛id列表
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);

        //根据竞赛id列表得到竞赛详情列表
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        if (CollectionUtil.isEmpty(examVOList)) {
            //说明redis中数据可能有问题 从数据库中查数据并且重新刷新缓存
            //从数据库中获取数据
            examVOList = getExamListByDB(examQueryDTO);
            //刷新缓存
            refreshCache(examQueryDTO.getType(),userId);
        }
        return examVOList;
    }

    /**
     * 从数据库中重新获取竞赛数据,并刷新缓存
     * @param examListType 竞赛列表的类型
     * @param userId userId
     */
    public void refreshCache(Integer examListType,Long userId) {
        List<Exam> examList = new ArrayList<>();
        if (ExamListType.UNFINISHED_EXAM_LIST.getValue().equals(examListType)) {
            //查询未完赛的竞赛列表
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    //gt: greater than 大于> (大于当前时间-->未完赛竞赛)
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    //eq: equal status=TRUE(1) --> 已发布
                    .eq(Exam::getStatus, Constant.TRUE)
                    //按创建时间降序排序 (新创建的在前面)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.HISTORY_EXAM_LIST.getValue().equals(examListType)) {
            //查询历史竞赛
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    //le: less than or equal 小于等于<= (小于等于当前时间-->历史竞赛)
                    .le(Exam::getEndTime, LocalDateTime.now())
                    //eq: equal  status=TRUE(1) --> 已发布
                    .eq(Exam::getStatus, Constant.TRUE)
                    //按创建时间降序排序 (新创建的在前面)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.USER_SIGNED_UP_EXAM_LIST.getValue().equals(examListType)) {
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);
            examList = BeanUtil.copyToList(examVOList, Exam.class);
        }
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }

        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap);  //刷新详情缓存
        redisService.deleteObject(getExamListKey(examListType, userId));
        redisService.rightPushAll(getExamListKey(examListType, userId), examIdList); //刷新列表缓存
    }
    
    /**
     * 获取题目竞赛列表的大小
     * @param examId 竞赛id
     * @return 返回竞赛题目列表大小
     */

    public Long getExamQuestionListSize(Long examId){
        String examQuestionKey = getExamQuestionListKey(examId);
        return redisService.getListSize(examQuestionKey);
    }

    /**
     * 获取到竞赛题目列表的第一个题目
     * @param examId 竞赛id
     * @return 返回id
     */
    public Long getFirstQuestionId(Long examId){
        return redisService.indexForList(getExamQuestionListKey(examId),0,Long.class);
    }

    /**
     * 刷新竞赛题目列表
     * @param examId 竞赛id
     */
    public void refreshExamQuestionCache(Long examId){
        //1.首先从数据库中去查出当前竞赛对应的所有题目id
        //SELECT question_id
        //FROM exam_question
        //WHERE exam_id = #{examId}
        //ORDER BY question_order ASC;
        List<ExamQuestion> examQuestionList = examQuestionMapper.selectList(new LambdaQueryWrapper<ExamQuestion>()
                .select(ExamQuestion::getQuestionId)
                .eq(ExamQuestion::getExamId,examId)
                .orderByAsc(ExamQuestion::getQuestionOrder));
        List<Long> questionIdList = new ArrayList<>();
        
        //如果为空,直接返回
        if (CollectionUtil.isEmpty(examQuestionList)){
            return;
        }

        //2.将获取到的题目id列表设置进questionIdList中
        for (ExamQuestion examQuestion : examQuestionList){
            questionIdList.add(examQuestion.getQuestionId());
        }

        //3.将当前竞赛对应的题目id列表保存到缓存中
        redisService.rightPushAll(getExamQuestionListKey(examId),questionIdList);

        //由于竞赛大多数在当天完成,所以我们需要定时刷新缓存
        //4.计算当前时间到次日0点的秒数并将其作为过期时间设置给 对应竞赛id列表的key
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(),
                LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
        redisService.expire(getExamQuestionListKey(examId), seconds, TimeUnit.SECONDS);
    }

    /**
     * 获取前一题的id
     * @param examId 当前竞赛id
     * @param questionId 当前题目id
     * @return 前一题的id
     */
    public Long preQuestion(Long examId, Long questionId) {
        //获取到当前题目在list中的下标
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId),questionId);
        if (index == 0){
            //如果等于0,说明已经是第一题了
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        //获取到前一个题目(index-1)在list中的id
        return redisService.indexForList(getExamQuestionListKey(examId),index-1,Long.class);
    }

    /**
     * 获取后一题的id
     * @param questionId 当前题目id
     * @return 返回后一题id
     */
    public Long nextQuestion(Long examId,Long questionId){

        //size记录列表大小
        Long size = getExamQuestionListSize(examId);
        //获取到当前题目在list中的下标
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId),questionId);
        if (index == size-1){
            //如果等于size-1,说明已经是最后一题了
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        //获取到后一个题目(index+1)在list中的id
        return redisService.indexForList(getExamQuestionListKey(examId),index+1,Long.class);
    }

    /**
     * 从缓存中获取指定竞赛的排名列表的大小
     * @param examId 竞赛id
     * @return 返回大小
     */
    public Long getRankListSize(Long examId) {
        return redisService.getListSize(getExamRankListKey(examId));
    }

    /**
     * 刷新竞赛排名列表
     * @param examId 竞赛id
     */
    public void refreshExamRankCache(Long examId){
        //这里之所以不用service中的List<ExamRankVO>,是因为那个设置了分页,我们需要保存全量数据
        List<ExamRankVO> examRankVOList = userExamMapper.selectExamRankList(examId);
        if (CollectionUtil.isEmpty(examRankVOList)){
            return;
        }
        //放入缓存
        redisService.rightPushAll(getExamRankListKey(examId),examRankVOList);
    }

    /**
     * 从缓存中获取到指定页数的竞赛排名信息
     * @param examRankDTO 里面就是examId
     * @return 返回定页数的竞赛排名信息
     */
    public List<ExamRankVO> getExamRankList(ExamRankDTO examRankDTO){
        //开始下标
        int start = (examRankDTO.getPageNum()-1) * examRankDTO.getPageNum();
        //结束下标
        int end = start + examRankDTO.getPageSize() - 1;

        return redisService.getCacheListByRange(getExamRankListKey(examRankDTO.getExamId()),start,end, ExamRankVO.class);
    }

    /**
     * 从数据库中重新获取数据
     * @param examQueryDTO 竞赛查询参数
     * @return 返回竞赛详细信息列表
     */
    private List<ExamVO> getExamListByDB(ExamQueryDTO examQueryDTO) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        //查询C端的竞赛列表
        return examMapper.selectExamList(examQueryDTO);
    }

    /**
     * 根据Redis中列表存储的竞赛id,把这些竞赛的详细信息都获取出来
     * @param examIdList 竞赛id列表
     * @return 返回竞赛详细信息列表
     */
    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {

        if (CollectionUtil.isEmpty(examIdList)) {
            //如果竞赛id列表为空 --> 说明redis当中没有数据,从数据库中查数据并且重新刷新缓存
            return null;
        }

        //将竞赛详情key存储到一个list中
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId));
        }

        //从Redis中获取所有竞赛的详细信息,不存在返回null
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);

        CollUtil.removeNull(examVOList); //去除列表中所有为null的信息

        if (CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()) {
            //如果竞赛详情结果为空 或者 竞赛详情数量和examId的数量不一致,说明redis中有不合法的竞赛
            // --> 从数据库中查数据并且重新刷新缓存
            return null;
        }
        return examVOList;
    }

    //拼接存储竞赛详细信息的key
    private String getExamListKey(Integer examListType, Long userId) {
        if (ExamListType.UNFINISHED_EXAM_LIST.getValue().equals(examListType)) {
            //类型为未完赛的竞赛
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.HISTORY_EXAM_LIST.getValue().equals(examListType)) {
            //类型为历史竞赛
            return CacheConstants.EXAM_HISTORY_LIST;
        } else if (ExamListType.USER_SIGNED_UP_EXAM_LIST.getValue().equals(examListType)){
            //类型为用户已报名的竞赛
            return CacheConstants.USER_EXAM_LIST + userId;
        }
        return null;
    }

    //存储竞赛列表id的key
    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }
    private String getUserExamListKey(Long userId) {
        return CacheConstants.USER_EXAM_LIST + userId;
    }

    private String getExamQuestionListKey(Long examId){
        return CacheConstants.EXAM_QUESTION_LIST + examId;
    }

    private String getExamRankListKey(Long examId) {
        return CacheConstants.EXAM_RANK_LIST + examId;
    }
}
